<template>
  <div class="page-container hospital">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="医院详情"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="onClickLeft"
    />

    <!-- 医院基本信息 -->
    <div class="hospital-info">
      <div class="hospital-card">
        <div class="hospital-header">
          <div class="hospital-image">
            <img v-if="hospitalInfo.image" :src="hospitalInfo.image" :alt="hospitalInfo.name">
            <img v-else src="../../assets/images/hospital.png" :alt="hospitalInfo.name">
          </div>
          <div class="hospital-basic">
            <div class="hospital-name">{{ hospitalInfo.name }}</div>
            <div class="hospital-tags">
              <span class="tag">{{ hospitalInfo.tags[0] }}</span>
              <span class="tag">{{ hospitalInfo.tags[1] }}</span>
            </div>
            <div class="hospital-action">
              <van-button icon="phone-o" type="primary" size="small" plain @click="makeCall">电话咨询</van-button>
            </div>
          </div>
        </div>
        <div class="hospital-address" @click="showMap">
          <van-icon name="location-o" />
          <span>{{ hospitalInfo.address }}</span>
          <div class="address-right">
            <span class="nav-text">导航</span>
            <van-icon name="arrow" />
          </div>
        </div>
      </div>
    </div>

    <!-- 服务列表 -->
    <div class="service-list">
      <div class="section-title">在线预约您需要的服务</div>
      <div v-show="hospitalServicesPrice.length === 0" style="margin: 40px 100px;"> 该医院暂未提供任何服务</div>
      <van-cell-group inset>
        <van-cell
          v-for="service in hospitalServicesPrice"
          :key="service.id"
          :title="service.name"
          is-link
          @click="selectService(service)"
        >
          <template #icon>
            <div class="service-icon">
              <img :src="getServiceIcon(service.code)" alt="service-icon">
            </div>
          </template>
          <template #label>
            <div class="service-info">
              <div class="service-desc">{{ getServiceDesc(service.code) }}</div>
              <div class="service-price">{{ service.price }}元/次</div>
            </div>
          </template>
          <template #right-icon>
            <van-button type="primary" size="small" class="book-btn" @click.stop="selectService(service)">
              预约
            </van-button>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 医院介绍 -->
    <div class="hospital-intro">
      <div class="section-title">医院介绍</div>
      <div class="intro-content">
        {{ hospitalInfo.description }}
      </div>
    </div>

    <!-- 底部操作栏 -->
    <!-- <div class="bottom-bar">
      <van-button type="primary" block @click="makeAppointment">立即预约</van-button>
    </div> -->

    <!-- 添加地图弹窗 -->
    <van-popup
      v-model:show="showMapPopup"
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="map-container">
        <div class="map-header">
          <span class="title">{{ hospitalInfo.name }}</span>
          <van-icon name="cross" @click="showMapPopup = false" />
        </div>
        <div class="map-content">
          <div id="container" class="amap-container"></div>
        </div>
        <div class="map-footer">
          <van-button type="primary" block @click="startNavigation">开始导航</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { carouselApi, hospitalApi } from '@/api'
import AMapLoader from '@amap/amap-jsapi-loader'

const router = useRouter()
const route = useRoute()

// 地图相关变量
const showMapPopup = ref(false)
let map = null
let marker = null
let geolocation = null

// 医院信息
const hospitalInfo = ref({
  id: '',
  name: '某某医院',
  tags: ['三甲医院', '综合医院'],
  address: '某某市某某区某某街道',
  phone: '010-12345678',
  description: '某某医院创建于XXXX年，是一所集医疗、教学、科研、预防为一体的大型综合性三级甲等医院。医院设有内科、外科、妇产科、儿科等临床科室，拥有先进的医疗设备和专业的医疗团队。',
  // longitude: 116.397428,  // 添加经度
  // latitude: 39.90923,     // 添加纬度
  longitude: 114.058876,  // 添加经度
  latitude: 22.566490,     // 添加纬度
  createTime:'',//创建时间
  updateTime:'',//更新时间
  image:'',//图片地址
  summary:'',//医院简介
  services:''//医院服务
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 拨打电话
const makeCall = () => {
  window.location.href = 'tel:' + hospitalInfo.value.phone
}

// 初始化地图
const initMap = async () => {
  try {
    // 设置安全密钥
    window._AMapSecurityConfig = {
      securityJsCode: import.meta.env.VITE_AMAP_SECURITY_CODE
    }

    const AMap = await AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY,
      version: '2.0',
      plugins: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder']
    })

    // 创建地图实例
    map = new AMap.Map('container', {
      zoom: 15,
      center: [hospitalInfo.value.longitude, hospitalInfo.value.latitude],
      viewMode: '2D'
    })

    // 添加医院标记
    marker = new AMap.Marker({
      position: [hospitalInfo.value.longitude, hospitalInfo.value.latitude],
      title: hospitalInfo.value.name,
      animation: 'AMAP_ANIMATION_DROP'
    })
    map.add(marker)

    // 初始化定位插件
    geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      zoomToAccuracy: true,
      buttonPosition: 'RB'
    })
    map.addControl(geolocation)

  } catch (error) {
    console.error('地图加载失败：', error)
    showToast({
      message: error.message || '地图加载失败，请稍后重试',
      type: 'fail'
    })
  }
}

// 查看地图
const showMap = async () => {
  try {
    showMapPopup.value = true
    // 等待 DOM 更新后初始化地图
    await nextTick()
    if (!map) {
      await initMap()
    }
  } catch (error) {
    console.error('显示地图失败：', error)
    showToast({
      message: '显示地图失败，请稍后重试',
      type: 'fail'
    })
  }
}

// 开始导航
const startNavigation = () => {
  try {
    // 使用高德地图 URL API 进行导航
    const navigationUrl = `https://uri.amap.com/navigation?to=${hospitalInfo.value.longitude},${hospitalInfo.value.latitude},${encodeURIComponent(hospitalInfo.value.name)}&mode=car&policy=1&src=myapp&callnative=1`
    window.location.href = navigationUrl
  } catch (error) {
    console.error('导航失败：', error)
    showToast({
      message: '导航失败，请稍后重试',
      type: 'fail'
    })
  }
}

// 在组件卸载时销毁地图实例
onUnmounted(() => {
  if (map) {
    map.destroy()
    map = null
  }
})

// 立即预约
const makeAppointment = () => {
  router.push({
    path: '/service',
    query: {
      hospitalId: hospitalInfo.value.id
    }
  })
}
const hospitalMessage = ref({})
const uptadeHospitalInfo = () => {
  hospitalInfo.value.name = hospitalMessage.value.name
  hospitalInfo.value.tags = [hospitalMessage.value.grade,hospitalMessage.value.type]
  hospitalInfo.value.address = hospitalMessage.value.address
  hospitalInfo.value.description = hospitalMessage.value.description
  hospitalInfo.value.phone = hospitalMessage.value.phone
  hospitalInfo.value.longitude = Number(hospitalMessage.value.longitude)
  hospitalInfo.value.latitude = Number(hospitalMessage.value.latitude)
  hospitalInfo.value.createTime = hospitalMessage.value.createTime
  hospitalInfo.value.updateTime = hospitalMessage.value.updateTime
  hospitalInfo.value.image = hospitalMessage.value.image
  hospitalInfo.value.summary = hospitalMessage.value.summary
  hospitalInfo.value.id = hospitalMessage.value.id
  hospitalInfo.value.services = hospitalMessage.value.services
}
// 获取医院详情
const getHospitalDetail = () => {
  try {
    const hospitalData = route.query.hospitalData
    if (hospitalData) {
      hospitalMessage.value = JSON.parse(decodeURIComponent(hospitalData))
      // 更新医院信息
      uptadeHospitalInfo()

    }
  } catch (error) {
    console.error('解析医院数据失败：', error)
    showToast('获取医院信息失败')
  }
}
//医院服务信息
const hospitalServicesPrice = ref([])
const getHospitalServices = async (hospitalId) =>{
  let params = {
    hospitalId
  }
  try {
const res = await hospitalApi.getHospitalServices(params)
     if(res.code === 200){
      hospitalServicesPrice.value = res.data
    .filter(service => hospitalInfo.value.services.includes(service.code)  && service.status === 1)
    .map(service => {
      let name = '';
      switch (service.code) {
        case 1:
          name = '就医陪诊';
          break;
        case 2:
          name = '诊前约号';
          break;
        case 3:
          name = '送取就医结果';
          break;
        case 4:
          name = '代跑取药';
          break;
        case 5:
          name = '上门陪护';
          break;
        default:
          name = '未知服务';
          break;
      }

      return {
        id: service.id,
        code: service.code,
        price: service.price,
        status: service.status,
        name: name, // 添加 name 字段
      };
    });
     }else{
      showToast({
      message:'获取医院服务失败' + res.message,
      type: 'fail'
    })
  }
}catch (error) {
  showToast({
      message:'获取医院服务失败' + error,
      type: 'fail'
    })
  }
}

// 获取服务图标
const getServiceIcon = (code) => {
  // 这里可以根据不同的服务类型返回不同的图标
  switch (code) {
    case 1: // 就医陪诊
      return new URL('../../assets/images/jiuyipeizhen.png', import.meta.url).href
    case 2: // 诊前约号
      return new URL('../../assets/images/zhenqianyuehao.png', import.meta.url).href
    case 3: // 送取就医结果
      return new URL('../../assets/images/songqujieguo.png', import.meta.url).href
    case 4: // 代跑取药
      return new URL('../../assets/images/daipao.png', import.meta.url).href
    case 5: // 上门陪护
      return new URL('../../assets/images/shangmenpeihu.png', import.meta.url).href
    default:
      return new URL('../../assets/images/hospital.png', import.meta.url).href
  }
}

// 获取服务描述
const getServiceDesc = (code) => {
  switch (code) {
    case 1: // 就医陪诊
      return '就医陪诊，值得托付'
    case 2: // 诊前约号
      return '诊前约号，省心省力'
    case 3: // 送取就医结果
      return '送取结果，安全无忧'
    case 4: // 代跑取药
      return '代跑取药，高效贴心'
    case 5: // 上门陪护
      return '上门陪护，关怀备至'
    default:
      return '未知服务，暂不了解'
  }
}

// 选择服务
const selectService = (service) => {
  router.push({
    path: '/service',
    query: {
      hospitalId: service.id,
      serviceCode: service.code,
      name:service.name,
      status:service.status,
      type:service.name,
      price:service.price,
      hospitalName:hospitalInfo.value.name
    }
  })
}

onMounted( async() => {
  await getHospitalDetail()
  await getHospitalServices(hospitalInfo.value.id)
})
</script>

<style lang="scss" scoped>
.hospital {
  padding-bottom: 60px;

  .hospital-info {
    background: #fff;
    border-radius: 8px;
    width: 340px;
    margin: 12px auto;

    .hospital-card {
      // background: linear-gradient(to bottom, #5f5e5e, #ffffff);
      .hospital-header {
        position: relative;
        padding: 16px 16px 0;
        display: flex;
        gap: 12px;

        .hospital-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          overflow: hidden;
          flex-shrink: 0;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .hospital-basic {
          flex: 1;
          min-width: 0; // 防止文字溢出

          .hospital-name {
            font-size: 16px;
            font-weight: 800;
            color: #333;
            margin-bottom: 8px;
            line-height: 1.2;
          }

          .hospital-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;

            .tag {
              padding: 2px 8px;
              font-size: 12px;
              border-radius: 4px;
              background: rgba(7, 193, 96, 0.1);
              color: #07c160;

              &:last-child {
                background: rgba(59, 130, 246, 0.1);
                color: #3b82f6;
              }
            }
          }

          .hospital-action {
            .van-button {
              padding: 0 12px;
              height: 28px;
              border-radius: 14px;
              font-size: 12px;
            }
          }
        }
      }

      .hospital-address {
        margin-top: 12px;
        padding: 0 16px 16px;
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #666;
        cursor: pointer;

        .van-icon-location-o {
          margin-right: 4px;
          font-size: 16px;
          color: #999;
        }

        span {
          flex: 1;
          margin-right: 4px;
        }

        .address-right {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #999;

          .nav-text {
            font-size: 14px;
            margin: 0;
            flex: none;
          }

          .van-icon-arrow {
            font-size: 14px;
          }
        }
      }
    }
  }

  .section-title {
    padding: 10px 16px;
    font-size: 16px;
    font-weight: 800;
    color: var(--text-color);
  }

  .service-list {
    margin-bottom: 12px;
    background: #fff;
    border-radius: 8px;
    width: 340px;
    margin: auto;

    .van-cell {
      align-items: flex-start;
      padding: 16px;
    }

    .service-icon {
      width: 70px;
      height: 70px;
      margin-right: 12px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .service-info {
      margin-top: 4px;

      .service-desc {
        font-size: 12px;
        color: var(--text-color-secondary);
        margin-bottom: 4px;
      }

      .service-price {
        color: #ee0a24;
        font-size: 14px;
        font-weight: 500;

        &::before {
          content: '¥';
          font-size: 12px;
        }
      }
    }

    .book-btn {
      position: absolute;
      top: 35px;
      right: 10px;
      height: 28px;
      padding: 0 12px;
      font-size: 12px;
      border-radius: 5px;
    }
  }

  .hospital-intro {
    padding: 0 16px;

    .intro-content {
      padding: 16px;
      background: #fff;
      border-radius: 8px;
      font-size: 14px;
      line-height: 1.6;
      color: var(--text-color);
    }
  }

  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 8px 16px;
    background: #fff;
    border-top: 1px solid var(--border-color);
  }

  .map-container {
    height: 100%;
    display: flex;
    flex-direction: column;

    .map-header {
      padding: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid var(--border-color);

      .title {
        font-size: 16px;
        font-weight: 500;
      }

      .van-icon {
        font-size: 20px;
        cursor: pointer;
      }
    }

    .map-content {
      flex: 1;
      position: relative;

      .amap-container {
        width: 100%;
        height: 100%;
      }
    }

    .map-footer {
      padding: 16px;
      border-top: 1px solid var(--border-color);
    }
  }
}
</style> 